#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: exception_handlers.py
@contact: zwb15083976291@163.com
@time: 2021/10/09
"""
import os
import traceback

from rest_framework.views import exception_handler as default_exception_handler
import logging

# 异常处理器
from utils.responses import CommonResponse, CommonAPIResponseStatus


def exception_handler(exc, context):
    response = default_exception_handler(exc, context)
    if not response:
        data = getattr(context['request'], 'data')
        method = getattr(context['request'], 'method')
        view = type(context['view'])
        if os.environ.get("BLOG_PROJECT_ENV", "prod") == "prod":
            logging.getLogger("unknown_error").error(
                f"error class {view}  error msg:'{exc}',method:'{method}' data:'{data}'")
        # TODO 这里将会将视图中没有捕捉到的异常进行捕捉
        print(f"trace_back:{traceback.format_exc()}")
        response = CommonResponse(status=CommonAPIResponseStatus.SERVICE_UNAVAILABLE)

    return response
